const router = require('koa-router')()
const User = require('../dbs/models/user')
const jwt = require('jsonwebtoken')
const output = require('../middleware/output')

router.prefix('/aboutLogin')

router.post('/login', async function (ctx) {
  let code
  let information = ctx.request.body
  const result = await User.findOne({ phone: information.phone })
  if (result) {
    if (result.password === information.passWord) {
      const token = jwt.sign({ phone: information.phone },  'test', { expiresIn: 60 * 60 })
      ctx.body = {
        code: 0,
        msg: '登录成功',
        username: information.phone,
        token
      }
    } else {
      output(ctx, -1, '密码错误')
    }
  } else {
    output(ctx, -1, '这个账号还没有注册')
  }
})


router.post('/register', async function (ctx) {
  let code
  let msg
  const result = await User.find({phone: ctx.request.body.phone})
  if (result.length !== 0) {
    code = -1
    msg = "手机号已被注册"
  } else {
    const user = new User({ phone: ctx.request.body.phone, password: ctx.request.body.password})
    try {
      await user.save()
      code = 0
      msg = "注册成功"
    } catch (error) {
      code = -1
      msg = "注册失败"
    }
  }
  ctx.body = {
    code,
    msg
  }
})

router.get('/logout', async function (ctx) {
  let code, msg
  ctx.body = {
    code: 0,
    msg: '退出成功'
  }
})

/** 找回密码第一步 */
router.post('/findPass', async (ctx) => {
  let code, msg
  try {
    let result = await User.findOne({ phone: ctx.request.body.phone })
    if (result) {
      ctx.body = {
        phone: result.phone,
        code: 0,
        msg: '查询成功'
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '查询失败'
      }
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      msg: '查询失败'
    }
  }
})

/** 修改密码 */
router.post('/changePass', async (ctx) => {
  let { password, phone } = ctx.request.body
  let msg, code
  try {
    let result = await User.update({ phone }, { password })
    ctx.body = {
      code: 0,
      msg: '成功'
    }
  } catch (error) {
    ctx.body = {
      code: 0,
      msg: '失败'
    }
  }
})

module.exports = router